package WiFi;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import client.ClientConnectable;
import exception.NFCException;

public class WiFiConnectedThread extends Thread {
	private Socket socket;
	private InputStream objInStream;
	private OutputStream objOutStream;
	private ClientConnectable client;
	private boolean keepAlive;

	public WiFiConnectedThread(Socket socket, ClientConnectable client) {
		this.socket = socket;
		this.client = client;		
		InputStream tmpObjInput = null;
		OutputStream tmpObjOutput = null;

		// Get the BluetoothSocket input and output streams
		try {
			tmpObjInput = this.socket.getInputStream();
			tmpObjOutput = this.socket.getOutputStream();
		} catch (IOException e) {
			System.err.println("temp sockets not created");
		}
		keepAlive= true;

		this.objInStream = tmpObjInput;
		this.objOutStream = tmpObjOutput;
		System.out.println("### ConnectedThread criada com " + socket.getInetAddress().getHostName());
	}

	public void run() {
		//System.out.println(	"### BEGIN WiFIConnectedThread");
		

		// Keep listening to the InputStream while connected
		while (keepAlive) {
			try {
				byte[] buffer = new byte[8*1024];
				// Read from the InputStream
				int bytes = objInStream.read(buffer);

				// Send the obtained bytes to the UI Activity
				if(bytes == -1)
					return;
				
				client.receiveData(buffer);
				String out = new String(buffer);				
				System.err.println("### [WIFI] Mensagem recebida: " + out.substring(0,5));
				//this.write(out.substring(4, 5).getBytes());
				//this.write(buffer);
				buffer = null;
				
			} catch (IOException e) {
				System.err.println("###  WiFIConnectedThread disconnected");
				cancel();
				//WiFiConnectToThread wct = new WiFiConnectToThread(socket.getInetAddress().getHostName(), client);
				//wct.start();
				break;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void write(byte[] buffer) throws NFCException {
		try {			
			objOutStream.write(buffer);
			objOutStream.flush();
		} catch (IOException e) {
			System.err.println("Exception during write wiFi  e=" + e.getMessage());
			throw new NFCException("Error during WiFi writing.. " + e.getMessage());
		}
	}

	public void cancel() {
		keepAlive = false;
		close();
	}

	public void close() {
		try {
			this.objInStream.close();
			this.objOutStream.close();
			this.socket.close();
			this.interrupt();
		} catch (IOException e) {
			System.err.println(	"server.close() of  WiFiServerThread failed");
		}
	}
}
